import { ABaseDecision } from "GameLoop/DecisionMaking/BaseDecision";
import { CoreEntity } from "GameLoop/WorldState/EntityManager/Entitys";
import { FactoryTaskHelper } from "GameLoop/WorldState/EntityManager/Entitys/room/factory/FactoryTaskHelper";
import { BASE_PRODUCE, BASE_PRUDUCE_TARGETS, COMMODITY_MAX, COMMODITY_PRODUCE_LIMIT, FactoryLevel, NormalProduct, TOP_TARGET } from "GameLoop/WorldState/EntityManager/Entitys/room/factory/constants";
import { GlobalResource } from "GameLoop/WorldState/mount/global/store/GlobalResource";
import { CoreTaskHelper } from "utils/task/coreTaskHelper";

/**
 * 生产线决策
 */
export class ProduceLineDecision < T extends TaskType="room"> extends ABaseDecision<T>
{
    constructor(WorldGetter:WorldGetter)
    {
        super(WorldGetter)
       
    }
    

    public isExpired(event: NormalEvent, region: string): boolean 
    {

        return true;
    }
    
    public makeTask(event: NormalEvent, region: string): IDecisionCode<T>|false
    {
        const produceLineRoom:Record<string,string[]>={"5":[],"4":[],"3":[],"2":[],"1":[],"0":[]};
        const globalstore = global.resourceStats;
        for(let room of globalstore.myrooms)
        {

            if( Game.rooms[room].controller?.level as number>7)
            {
                const coreentity =  Game.rooms[room].getEntity("CoreEntity");
                if(coreentity && coreentity.Factory)
                {
                    if(Game.rooms[room].getTaskByType("factory").length>3)
                    {
                        continue;
                    }
                    if(coreentity.Factory.level)
                    {
                        produceLineRoom[coreentity.Factory.level].push(room);
                    }
                    else
                    {
                        produceLineRoom["0"].push(room);
                    }

                }
            }

        }

        global.Log.Info(`生产线房间 ;${JSON.stringify(produceLineRoom)}`);
        // 判断主要原料。数量
        for(const level in produceLineRoom)
        {
            const factorylevel = parseInt(level);
            for(const roomName of produceLineRoom[level])
            {
                this.postProduceTask( globalstore,roomName,factorylevel);
            }
        }
        return false
    }
    
    private postProduceTask( globalstore:GlobalResource,roomName:string,factorylevel:number)
    {
        const coreentity = Game.rooms[roomName].getEntity("CoreEntity");
        let target=  this.getPrudeceTarget(globalstore,coreentity,factorylevel);
        // if(!target)
        // {
        //     target  = this.getBaseProduceTarget(coreentity);
        //     // 啥都生产不了,生产基础原材料
        // }
        
        if(target)
        {
            // 发布任务
            global.Log.Info(`${roomName} 获取生产 目标 ---生产线   ${JSON.stringify(target)}`);
            // const producearg=  FactoryTaskHelper.getProduceTaskArg(target.target,target.amount);
            //const task  =  CoreTaskHelper.getProduce(target.target,target.amount)
            
            Game.rooms[roomName].getNodeHeap().produceLineGoal = {resourceType:target.target,amount:target.amount};
            Memory.Debug[`生产目标${roomName}`] = `${target.target}:${target.amount}  ${Game.time}`
            //Game.rooms[roomName].addNewTask(task);
            // const factorytask =  FactoryTaskHelper.getTask("produce_"+ roomName,roomName,producearg,"produce");
            // coreentity.addTask(factorytask);
            //global.Log.Info(`投递生产任务${produceLineRoom[level]} ->${JSON.stringify(factorytask)}`);
        }
        else
        {
            global.Log.Warning(`${roomName} 获取生产 目标 ---生产线   无`);
        }
    }
    private getBaseProduceTarget(coreentity:CoreEntity)
    {
        let amount=1000
        for(const key in BASE_PRODUCE)
        {
            if(this.isProduceResourceReady(coreentity,key as CommodityConstant,10))
            {
                let target:ITargetParam={target:key as CommodityConstant,amount:amount/5,number:0};
                return target
            }

        }
        return undefined;
    }

    //
    /**
     * 根据库存资源，和房间工厂等级。判断应该生产什么
    */
    private getPrudeceTarget(globalstore:GlobalResource,core:CoreEntity,level:number):ITargetParam|undefined
    {
        switch(level)
        {
            case 1:
                return this.getPrudeceTarget_Level1(globalstore,core,level);
            case 2:
            case 3:
            case 4:
            case 5:
                return this.getPrudeceTarget_Level2_5(globalstore,core,level);
        }

        return undefined
    }

    private getPrudeceTarget_Level1(globalstore:GlobalResource,core:CoreEntity,level:number):ITargetParam|undefined
    {
        const radio = 20;//*28;
        if(globalstore.getUseCapacity(RESOURCE_COMPOSITE)<COMMODITY_MAX[RESOURCE_COMPOSITE])
        {
            return {target:RESOURCE_COMPOSITE,amount:1000,number:0}
        }
        
        for(const item of BASE_PRUDUCE_TARGETS)
        {
            if(globalstore.getUseCapacity(item.target)>COMMODITY_PRODUCE_LIMIT[1])
            {
                // 1级商品的数量限制
                continue;
            }
            // 1.首先判断我自己的房间资源够不够
            if(core.resourceCount(item.base)>=item.number*radio)
            {
                const amount = COMMODITIES[item.target].amount *radio;
                return {target:item.target,amount:amount,number:0}
            }
            // 然后判断全局的富余资源够不够

            if(globalstore.getUseCapacity(item.base)>=item.number*radio)
            {
                const amount = COMMODITIES[item.target].amount *radio;
                return {target:item.target,amount:amount,number:0}
            }
        }
        return undefined
    }

    private getPrudeceTarget_Level2_5(globalstore:GlobalResource,core:CoreEntity,level:FactoryLevel):ITargetParam|undefined
    {
        let time = 1;
        if(level==2)
        {
            time=10;
        }
        // 如果 2-3级没有东西合成
        // 2级则合成 crystal
        // 3级则合成 liquid
        if(level == 3 && globalstore.getSurplusResource(RESOURCE_LIQUID)<COMMODITY_MAX[RESOURCE_LIQUID])
        {
            if(this.isProduceResourceReady(core,RESOURCE_LIQUID,10))
            {
                return {target:RESOURCE_LIQUID,amount:120,number:0}
            }

        }
        for(let type in TOP_TARGET)
        {
            if(TOP_TARGET[type][level])
            {
              
                const curtarget = TOP_TARGET[type][level][0];
                if(COMMODITY_PRODUCE_LIMIT[level] && globalstore.getUseCapacity(curtarget)>COMMODITY_PRODUCE_LIMIT[level])
                {
                    // 2-5级商品的数量限制
                    continue;
                }
                if(this.isCanbeProduce(globalstore,core,curtarget,time))
                {
                    const amount = COMMODITIES[curtarget].amount *time;
                    Memory.Debug[`商品可以生产:${type}`] = amount
                    return {target:curtarget,amount:amount,number:0}
                }
                Memory.Debug[`商品不可以生产:${type}`] = time
            }
        }
        {
            // 对基础商品进行压缩
        }
        return undefined
    }

    /**
     * 判断商品是否可以生产，主要依据子商品 需要有等级生产要求的产业链商品，
     * 复杂在于,不同商品要求的子原料可能不是按等级递增的，所以最好还是配置一个表格。(因为规律不明显) 查表来做 **!!!!!!
    */
    private isCanbeProduce(globalstore:GlobalResource,core:CoreEntity,target:CommodityConstant,time:number):boolean
    {
        return globalstore.isCanbeProduce(target,time);
        // const targetamount = COMMODITIES[target].amount*time;
        // //const submap:Record<string,number>={};
        // const subconstants = COMMODITIES[target].components;
        // let bcanProduce = true;
        // for(const subconstant in  subconstants)
        // {
        //     // 1.需要op 工厂生产的
        //     if(COMMODITIES[subconstant as CommodityConstant].level)
        //     {
        //         // 除去普通商品之外的需要等级生产的商品
        //         //if(!NormalProduct.has(subconstant as CommodityConstant))
        //         {
        //             // bflag = true;
        //             const amount = FactoryTaskHelper.ClacSubResourceAmount(target as CommodityConstant,targetamount,subconstant as FactoryResourceType);
        //             //submap[subconstant]=amount;
        //             if(globalstore.getSurplusResource(subconstant as ResourceConstant)<amount  && core.resourceCount(subconstant as ResourceConstant)<amount)
        //             {
        //                 core.room.registerShortageResource(subconstant as ResourceConstant,amount);
        //                 // 子资源不足
        //                 this.debugIsProduce(target,time,`低级区域商品 ${subconstant} 数量小于 ${amount} `)
        //                 bcanProduce = false;
        //                 // return false;
        //             }
        //         }
        //     }
        //     else
        //     {
        //         if(BASE_PRODUCE[subconstant])
        //         {
        //             const amount = FactoryTaskHelper.ClacSubResourceAmount(target as CommodityConstant,targetamount,subconstant as FactoryResourceType);
        //             if(globalstore.getSurplusResource(subconstant as ResourceConstant)<amount  && core.resourceCount(subconstant as ResourceConstant)<amount)
        //             {
        //                 this.debugIsProduce(target,time,`原材料 ${subconstant} 数量小于 ${amount} `)
        //                 return false;
        //             }

        //         }
        //     }
        //     // 2.不需要op工厂生产的
        // }
        // return bcanProduce
    }

    private debugIsProduce(type:CommodityConstant,amount:number,error:string)
    {
        // if(type == RESOURCE_FRAME)
        {
           Memory.Debug[`商品生产:${type}`]=(`是否可以生产${type} ${ amount} 结果:${error}`);
        }
    }

    private isProduceResourceReady(store:CoreEntity,target:CommodityConstant,time:number):boolean
    {
        // if(!COMMODITIES[target].level)
        {
            const childrecord = FactoryTaskHelper.getProductComposeRecord(target);
            for(const k in childrecord)
            {
                if(store.resourceCount(k as ResourceConstant)<childrecord[k as ResourceConstant]*time )
                {
                    // 子资源不足
                    return false;
                }
            }
            return true;
        }

    }
}